﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win;
using Dashboard.ProductBonus.Business;
using System.Globalization;

namespace Dashboard.ProductBonus
{
    public partial class FormAddNonproductiveTime : Form
    {
        private ValueList _valueListReason = new ValueList();
        private DataTable _dataSource = new DataTable();

        public FormAddNonproductiveTime()
        {
            InitializeComponent();
        }

        private void FormAddNonproductiveTime_Load(object sender, EventArgs e)
        {
            this.textBoxDate.Text = DateTime.Now.AddDays(-1).Date.ToString("yyyyMMdd");
            this.GenerateGridDataSource();
            this.BindReasonList();
        }

        private void ultraGridMain_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            // 自适应列宽
            e.Layout.AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.None;
            e.Layout.Override.AllowColSizing = AllowColSizing.Free;
            e.Layout.Override.AllowColMoving = AllowColMoving.NotAllowed;

            // 设置Grid的Split窗口个数，建议设置为1--不允许Split
            e.Layout.MaxColScrollRegions = 1;
            e.Layout.MaxRowScrollRegions = 1;

            // 冻结列
            e.Layout.UseFixedHeaders = false;

            // 排序
            e.Layout.Override.HeaderClickAction = Infragistics.Win.UltraWinGrid.HeaderClickAction.SortSingle;

            // 不允许删除
            e.Layout.Override.AllowDelete = DefaultableBoolean.False;

            // 滚动提示
            e.Layout.Bands[0].ScrollTipField = "StaffNo";

            // 设置编辑模式
            for (int i = 0; i < e.Layout.Bands[0].Columns.Count; i++)
            {
                e.Layout.Bands[0].Columns[i].CellActivation = Activation.NoEdit;
            }

            e.Layout.Bands[0].Columns["Reason"].ValueList = this._valueListReason;
            //e.Layout.Bands[0].Columns["Reason"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownList;
        }

        private void BindReasonList()
        {
            _valueListReason.ValueListItems.Clear();
            _valueListReason.ValueListItems.Add("", "");

            BusinessBase bb = new BusinessBase();
            DataTable reasons = bb.GetAllReasonList();

            foreach (DataRow row in reasons.Rows)
            {
                if (row["pcode"].ToString() == "16")
                {
                    continue;
                }
                _valueListReason.ValueListItems.Add(row["pcode"].ToString(), row["pcode"].ToString() + "-" + row["pdesc"].ToString());
            }
        }

        private void textBoxStaffNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                if (this.textBoxStaffNo.Text == "")
                {
                    this.textBoxStaffNo.Focus();
                    return;
                }

                // 获取Staff的相关信息
                if (this.GetStaffInfo())
                {
                    this.textBoxDate.Focus();
                    this.textBoxDate.SelectAll();
                }
            }
        }

        private bool GetStaffInfo()
        {
            // 获取Staff的相关信息
            BusinessBase bb = new BusinessBase();
            DataTable staffInfo = bb.GetStaffInfo(this.textBoxStaffNo.Text.Trim());

            if (staffInfo.Rows.Count > 0)
            {
                this.textBoxName.Text = staffInfo.Rows[0]["Name"].ToString();
                this.textBoxTeam.Text = staffInfo.Rows[0]["Team"].ToString();
                this.textBoxShift.Text = staffInfo.Rows[0]["Shift"].ToString();

                return true;
            }
            else
            {
                this.textBoxName.Text = string.Empty;
                this.textBoxTeam.Text = string.Empty;
                this.textBoxShift.Text = string.Empty;

                MessageBox.Show(this, "Staff No is invalid.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.textBoxStaffNo.Focus();
                this.textBoxStaffNo.SelectAll();
                return false;
            }
        }

        private bool GetReasonInfo()
        {
            string reasonCode = this.textBoxReasonCode.Text.Trim();
            BusinessBase bb = new BusinessBase();
            DataTable reasonInfo = bb.GetReasonInfo(reasonCode);
            if (reasonInfo.Rows.Count > 0)
            {
                this.textBoxReasonDesc.Text = reasonInfo.Rows[0]["pdesc"].ToString();

                return true;
            }
            else
            {
                this.textBoxReasonDesc.Text = string.Empty;

                MessageBox.Show(this, "Reason code is invalid.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.textBoxReasonCode.Focus();
                this.textBoxReasonCode.SelectAll();
                return false;
            }
        }

        private void toolStripButtonCreate_Click(object sender, EventArgs e)
        {
            this.ResetUI();
        }

        private void toolStripButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (this.DoSave())
                {
                    this.ResetUI();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void toolStripButtonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ResetUI()
        {
            this.textBoxStaffNo.Text = string.Empty;
            this.textBoxName.Text = string.Empty;
            this.textBoxTeam.Text = string.Empty;
            this.textBoxShift.Text = string.Empty;
            //this.textBoxDate.Text = DateTime.Now.AddDays(-1).Date.ToString("yyyyMMdd");
            this.textBoxReasonCode.Text = string.Empty;
            this.textBoxReasonDesc.Text = string.Empty;
            this.textBoxTotalHour.Text = string.Empty;
            this.textBoxFromTime.Text = ":";
            this.textboxToTime.Text = ":";

            this.textBoxStaffNo.Focus();
            this.textBoxStaffNo.SelectAll();
        }

        private bool DoUICheck()
        {
            #region StaffNo Field
            if (this.textBoxStaffNo.Text == string.Empty)
            {
                MessageBox.Show(this, "Staff No is required.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.textBoxStaffNo.Focus();
                return false;
            }

            if (!this.GetStaffInfo())
            {
                return false;
            }
            #endregion

            #region Date Field
            if (this.textBoxDate.Text == string.Empty)
            {
                MessageBox.Show(this, "Date is required.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.textBoxDate.Focus();
                return false;
            }

            if (!this.CheckDate())
            {
                return false;
            }
            #endregion

            #region Reason Field
            if (this.textBoxReasonCode.Text == string.Empty)
            {
                MessageBox.Show(this, "Reason is required.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.textBoxReasonCode.Focus();
                return false;
            }

            if (!this.GetReasonInfo())
            {
                return false;
            }
            #endregion

            #region Total Hour Field
            if (this.textBoxTotalHour.Text == string.Empty)
            {
                MessageBox.Show(this, "Total Hour is required.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.textBoxTotalHour.Focus();
                return false;
            }

            if (!this.CheckTotalHour())
            {
                return false;
            }
            #endregion

            if (!this.CheckFromTime())
            {
                return false;
            }

            if (!this.CheckToTime())
            {
                return false;
            }

            return true;
        }

        private bool DoSave()
        {
            if (!this.DoUICheck())
            {
                return false;
            }

            // 保存数据
            string staffNo = this.textBoxStaffNo.Text.Trim();
            string reasonCode = this.textBoxReasonCode.Text.Trim();
            string reasonName = this.textBoxReasonDesc.Text.Trim();
            DateTime date = DateTime.ParseExact(this.textBoxDate.Text.Trim(), "yyyyMMdd", new CultureInfo("en-US"));
            int totalTime = int.Parse(this.textBoxTotalHour.Text.Trim());
            string fromTime = this.textBoxFromTime.Text.Trim() == ":" ? "null" : "'" + DateTime.ParseExact(this.textBoxFromTime.Text, "HH:mm", new CultureInfo("en-US")).ToString("HH:mm") + "'";
            string toTime = this.textboxToTime.Text.Trim() == ":" ? "null" : "'" + DateTime.ParseExact(this.textboxToTime.Text, "HH:mm", new CultureInfo("en-US")).ToString("HH:mm") + "'";

            UnproductiveTime ut = new UnproductiveTime();
            if (ut.ExistUnproductiveTime(staffNo, date, reasonCode))
            {
                MessageBox.Show(this, string.Format("There is already an " + reasonName + " record of the date [{0}] for this staff [{1}].", date.ToString("yyyy-MM-dd"), staffNo), "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            string sql = string.Format(@"
     INSERT INTO AbnormalWorkingTime
           (StaffNo
           ,TimeType
           ,ReasonCode
           ,Date
           ,FromTime
           ,ToTime
           ,TotalTime
           ,InsertBy
           ,InsertDate
           ,UpdatedBy
           ,UpdatedDate)
     VALUES
           ('{0}'
           ,'UT'
           ,'{1}'
           ,'{2}'
           ,{3}
           ,{4}
           ,'{5}'
           ,'{6}'
           ,getdate()
           ,'{7}'
           ,getdate())", staffNo, reasonCode, date.ToString("yyyy-MM-dd"), fromTime, toTime, totalTime, CommonBusiness.GetCurrentLoginUser(), CommonBusiness.GetCurrentLoginUser());

            new UnproductiveTime().AddSingleUnproductiveTime(sql);

            // 将该记录加入到Grid的数据源中
            DataRow dr = this._dataSource.NewRow();
            dr.ItemArray = new object[] { staffNo, this.textBoxName.Text.Trim(), this.textBoxTeam.Text.Trim(),
                                                     this.textBoxShift.Text.Trim(), date, reasonCode, totalTime, 
                                                     (fromTime=="null" ? null : fromTime.Replace("'","")), 
                                                     (toTime == "null" ? null : toTime.Replace("'","")) };
            this._dataSource.Rows.InsertAt(dr, 0);
            //this._dataSource.Rows.Add(new object[] { staffNo, this.textBoxName.Text.Trim(), this.textBoxTeam.Text.Trim(),
            //                                         this.textBoxShift.Text.Trim(), date, reasonCode, totalTime, 
            //                                         (fromTime=="null" ? null : fromTime.Replace("'","")), 
            //                                         (toTime == "null" ? null : toTime.Replace("'","")) });
            this._dataSource.AcceptChanges();
            this.ultraGridMain.ActiveRow = this.ultraGridMain.Rows[0];
            return true;
        }

        private void GenerateGridDataSource()
        {
            _dataSource = new DataTable();

            _dataSource.Columns.Add("StaffNo", typeof(string));
            _dataSource.Columns.Add("StaffName", typeof(string));
            _dataSource.Columns.Add("Team", typeof(string));
            _dataSource.Columns.Add("Shift", typeof(string));
            _dataSource.Columns.Add("Date", typeof(DateTime));
            _dataSource.Columns.Add("Reason", typeof(string));
            _dataSource.Columns.Add("TotalTime", typeof(int));
            _dataSource.Columns.Add("FromTime", typeof(string));
            _dataSource.Columns.Add("ToTime", typeof(string));

            _dataSource.AcceptChanges();

            this.ultraGridMain.DataSource = _dataSource;
            this.ultraGridMain.DataBind();
        }
        private void textBoxReasonCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                if (string.IsNullOrEmpty(this.textBoxReasonCode.Text.Trim()))
                {
                    this.textBoxReasonCode.Focus();
                    return;
                }

                if (this.GetReasonInfo())
                {
                    this.textBoxTotalHour.Focus();
                    this.textBoxTotalHour.SelectAll();
                }
            }
        }

        private void textBoxTotalHour_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                if (this.textBoxTotalHour.Text == string.Empty)
                {
                    this.textBoxTotalHour.Focus();
                    return;
                }

                if (this.CheckTotalHour())
                {
                    this.textBoxFromTime.Focus();
                    this.textBoxFromTime.SelectAll();
                }
            }
        }

        private void textBoxFromTime_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                if (this.CheckFromTime())
                {
                    this.textboxToTime.Focus();
                    this.textboxToTime.SelectAll();
                }
            }
        }

        private void textboxToTime_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                if (this.CheckToTime())
                {
                    // Save Data
                    this.toolStripButtonSave_Click(null, null);
                }
            }
        }

        private void textBoxDate_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                if (this.textBoxDate.Text == string.Empty)
                {
                    this.textBoxDate.Focus();
                    return;
                }

                if (this.CheckDate())
                {
                    this.textBoxReasonCode.Focus();
                    this.textBoxReasonCode.SelectAll();
                }
            }
        }

        private bool CheckDate()
        {
            DateTime date;
            bool isDateValid = DateTime.TryParseExact(this.textBoxDate.Text, "yyyyMMdd", new CultureInfo("en-US"), DateTimeStyles.None, out date);
            if (!isDateValid)
            {
                MessageBox.Show(this, "Date is invalid, please entry date in YYYYMMDD format.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.textBoxDate.Focus();
                this.textBoxDate.SelectAll();
                return false;
            }

            return true;
        }

        private bool CheckTotalHour()
        {
            int hour;
            bool isValid = int.TryParse(this.textBoxTotalHour.Text.Trim(), out hour);
            if (!isValid)
            {
                MessageBox.Show(this, "Total Hour is invalid, please entry a valid number.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.textBoxTotalHour.Focus();
                this.textBoxTotalHour.SelectAll();
                return false;
            }

            return true;
        }

        private bool CheckFromTime()
        {
            if (this.textBoxFromTime.Text.Trim() != ":")
            {
                // 验证时间格式是否正确
                DateTime dtFromTime;
                bool isValid = DateTime.TryParseExact(this.textBoxFromTime.Text, "HH:mm", new CultureInfo("en-US"), DateTimeStyles.None, out dtFromTime);
                if (!isValid)
                {
                    MessageBox.Show(this, "Time Start is invalid, please entry a valid time.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    this.textBoxFromTime.Focus();
                    this.textBoxFromTime.SelectAll();
                    return false;
                }
                else
                {
                    // 自动计算End Time
                    if (this.textBoxTotalHour.Text.Trim() != string.Empty)
                    {
                        int hour;
                        bool isHourValid = int.TryParse(this.textBoxTotalHour.Text.Trim(), out hour);
                        if (isHourValid)
                        {
                            DateTime dtToTime = dtFromTime.AddHours(hour);
                            this.textboxToTime.Text = dtToTime.ToString("HH:mm");
                        }
                    }
                    return true;
                }
            }
            else
            {
                return true;
            }
        }

        private bool CheckToTime()
        {
            if (this.textboxToTime.Text.Trim() != ":")
            {
                // 验证时间格式是否正确
                DateTime dtToTime;
                bool isValid = DateTime.TryParseExact(this.textboxToTime.Text, "HH:mm", new CultureInfo("en-US"), DateTimeStyles.None, out dtToTime);
                if (!isValid)
                {
                    MessageBox.Show(this, "Time End is invalid, please entry a valid time.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    this.textboxToTime.Focus();
                    this.textboxToTime.SelectAll();
                    return false;
                }
            }

            return true;
        }

        private void ultraGridMain_DoubleClickRow(object sender, DoubleClickRowEventArgs e)
        {
              if (MessageBox.Show(this, "Are you sure to delete the record?", "Confirm",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor; 
                    UnproductiveTime at = new UnproductiveTime();  
                    at.DeleteUnproductiveTime(e.Row.Cells["StaffNo"].Value.ToString(), Convert.ToDateTime(e.Row.Cells["Date"].Value), e.Row.Cells["Reason"].Value.ToString(),"UT");                    
                    e.Row.Delete(false);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
        }
    }
}
